//
//  LKTaiQianEditViewController.m
//  Mideleague_Shop
//
//  Created by Zhiwang on 2020/6/30.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKTaiQianEditViewController.h"
#import "LKUFPictureRow.h"
#import "LKUFPictureRowCell.h"
#import "LKUFOpenShopHeaderRow.h"
#import "LKUFOpenShopHeaderRowCell.h"
#import "LKUFOpenShopBottomButtonRow.h"
#import "LKUFOpenShopBottomButtonRowCell.h"
#import "LKSeeBillListViewController.h"
#import "LKBindAccountViewController.h"
#define scaleTopAndBottom(value) (value/667.0)*[UIScreen mainScreen].bounds.size.height

@interface LKTaiQianEditViewController ()
@property(nonatomic,strong)UFFormView *formview;
@property(nonatomic,strong)UIView *bgView;
@property(nonatomic,strong)UIImageView *erweimaImageV;
@end

@implementation LKTaiQianEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.operateStyle == LKTaiqianOperateStyleEdit) {
        self.navigationItem.title = @"编辑台签";
        [self createFormView];
        [self createBottomBtnAndCodeImage];
    }else{
        self.navigationItem.title = @"添加台签";
        self.model = [[LKTaiqianModel alloc] init];
        [self createFormView];
    }
    [self setNavgationRightBtn];

    // Do any additional setup after loading the view.
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    LKBaseButton *rightBtn;
    if (self.operateStyle == LKTaiqianOperateStyleEdit) {
       rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"保存" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
           if ([NSString isBlankString:weakSelf.model.cate_name]) {
               [SVProgressHUD showInfoWithStatus:@"请输入台签名称"];
               return ;
           }
           if ([NSString isBlankString:weakSelf.model.checker_id]) {
               [SVProgressHUD showInfoWithStatus:@"请选择绑定收银员"];
               return ;
           }
            NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@"0",@"cate_id":weakSelf.model.Id,@"checker_id":weakSelf.model.checker_id,@"cate_name":weakSelf.model.cate_name}];
             NSString *sign = [NSString encoingWithDic:param];
             [param setObject:sign forKey:@"sign"];
             btn.enabled = NO;
             [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyTaiqianEditUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                 
             } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                 
                 if ([responseObject[@"code"] isEqualToString:@"success"]) {
                     [SVProgressHUD showInfoWithStatus:@"保存成功"];
                     [weakSelf.navigationController popViewControllerAnimated:YES];
                 }else{
                     btn.enabled = YES;
                     [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                 }
             } failure:^(NSString * _Nullable errorMessage) {
                    btn.enabled = YES;
             }];
        }];
    }else{
        rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"保存" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
            if ([NSString isBlankString:weakSelf.model.cate_name]) {
                [SVProgressHUD showInfoWithStatus:@"请输入台签名称"];
                return ;
            }
            if ([NSString isBlankString:weakSelf.model.checker_id]) {
                [SVProgressHUD showInfoWithStatus:@"请选择绑定收银员"];
                return ;
            }

             NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"cate_id":[NSString judegeIsNullAndTransform:weakSelf.cate_id],@"checker_id":[NSString judegeIsNullAndTransform:weakSelf.model.checker_id],@"cate_name":[NSString judegeIsNullAndTransform:weakSelf.model.cate_name]}];
              NSString *sign = [NSString encoingWithDic:param];
              [param setObject:sign forKey:@"sign"];
              btn.enabled = NO;
              [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyTaiqianAddUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                  
              } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                  if ([responseObject[@"code"] isEqualToString:@"success"]) {
                      [SVProgressHUD showInfoWithStatus:@"保存成功"];
                      [[NSNotificationCenter defaultCenter] postNotificationName:@"TaiqianPageReload" object:nil];
                      [weakSelf.navigationController popViewControllerAnimated:YES];
                  }else{
                      btn.enabled = YES;
                      [SVProgressHUD showInfoWithStatus:responseObject[@"data"]];
                  }
              } failure:^(NSString * _Nullable errorMessage) {
                      btn.enabled = YES;
              }];
         }];
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)createFormView{
    WS(weakSelf)
    self.formview = [UFFormView makeFormView:^(UFFormViewMaker * _Nonnull make) {
        make
        .registerRow([LKUFOpenShopHeaderRow class], [LKUFOpenShopHeaderRowCell class])
        .registerRow([LKUFPictureRow class], [LKUFPictureRowCell class])
        .registerRow([LKUFOpenShopBottomButtonRow class], [LKUFOpenShopBottomButtonRowCell class])
        .addSection([UFSection makeSection:^(UFSectionMaker * _Nonnull make) {
            make
            .titleStyle([UFRowTitleStyle makeTitleStyle:^(UFRowTitleStyleMaker * _Nonnull make) {
               make
                .width(WIDTH/2)
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor)
                .textAlignment(NSTextAlignmentLeft);
            }])
            .valueStyle([UFTextStyle makeTextStyle:^(UFRowTextStyleMaker * _Nonnull make) {
                make
                .textAlignment(NSTextAlignmentRight)
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .height(RowHeightDefault)
                .value(weakSelf.model.cate_name)

                .rowDidSelected(^(__kindof UFRow * _Nonnull row) {
                    
                })
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.model.cate_name = value;
                })
                .title(@"台签名称");
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .editable(NO)
                .height(RowHeightDefault)
                .value(weakSelf.model.user_name)
                .accessoryType(UFRowAccessoryDisclosureIndicator)
                .rowDidSelected(^(__kindof UFRow * _Nonnull row) {
                    LKBindAccountViewController *bindVc = [[LKBindAccountViewController alloc] init];
                    bindVc.valueBlock = ^(NSString * _Nonnull roleId, NSString * _Nonnull roleName) {
                        weakSelf.model.user_name = roleName;
                        weakSelf.model.checker_id = roleId;
                        [weakSelf.formview removeFromSuperview];
                        [weakSelf createFormView];
                    };
                    [weakSelf.navigationController pushViewController:bindVc animated:YES];
                })
                .title(@"绑定收银员");
            }]);
        }])
        .addToSuperView(self.view);
    }];
    self.formview.scrollEnabled = NO;
    [self.formview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT);
        make.height.mas_equalTo(scaleTopAndBottom(RowHeightDefault) * 2);
    }];
    

}
-(void)createBottomBtnAndCodeImage{
    WS(weakSelf)
    LKBaseButton *seeBillBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"查看流水" titleColor:[UIColor whiteColor] layercorne:scaleTopAndBottom(20) font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:yellowDefaultColor AndActionBlock:^(UIButton * _Nonnull btn) {
        LKSeeBillListViewController *vc = [[LKSeeBillListViewController alloc] init];
        vc.cate_id = weakSelf.model.Id;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    [self.view addSubview:seeBillBtn];
    [seeBillBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-10);
        make.height.mas_equalTo(scaleTopAndBottom(40));
        make.left.equalTo(self.view).offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    LKBaseButton *saveBtn = [LKBaseButton buttonWithFrame:CGRectZero type:UIButtonTypeCustom title:@"保存二维码到相册" titleColor:yellowDefaultColor layercorne:scaleTopAndBottom(20) font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor whiteColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        // 设置绘制图片的大小
        UIGraphicsBeginImageContextWithOptions(weakSelf.bgView.bounds.size, NO, 0.0);
        // 绘制图片
        [weakSelf.bgView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        // 保存图片到相册   如果需要获取保存成功的事件第二和第三个参数需要设置响应对象和方法，该方法为固定格式。
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(seeBillBtn.mas_top).offset(-10);
        make.height.mas_equalTo(scaleTopAndBottom(40));
        make.left.equalTo(self.view).offset(10);
        make.centerX.equalTo(self.view);
    }];
    saveBtn.layer.borderColor = yellowDefaultColor.CGColor;
    saveBtn.layer.borderWidth = 1;
    self.bgView = [self backPictureView];
    [self.view addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.top.equalTo(self.view.mas_top).offset(5 + NAVIGATION_BAR_HEIGHT + scaleTopAndBottom(104));
        make.bottom.equalTo(saveBtn.mas_top).offset(-10);
    }];
}
-(UIView *)backPictureView{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    LKBaseButton *headerBtn = [LKBaseButton buttonWithFrame:CGRectZero type:UIButtonTypeCustom title:@"    扫一扫付款" titleColor:COLOR_HEX(0x333333) layercorne:0 font:[UIFont fontWithName:@"PingFangSC-Medium" size: 16] backgroudColor:[UIColor whiteColor] AndActionBlock:^(UIButton * _Nonnull btn) {

    }];
    [headerBtn setImage:[UIImage imageNamed:@"AppIcon"] forState:UIControlStateNormal];
    [bgView addSubview:headerBtn];
    [headerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView.mas_top).offset(10);
        make.centerX.equalTo(bgView);
    }];
    
    self.erweimaImageV = [[UIImageView alloc] init];
    [self.erweimaImageV sd_setImageWithURL:[NSURL URLWithString:_model.barcode_img] placeholderImage:[UIImage imageNamed:@""]];
    [bgView addSubview:_erweimaImageV];
    [_erweimaImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerBtn.mas_bottom).offset(5);
        make.centerX.equalTo(bgView);
        make.size.mas_equalTo(CGSizeMake(scaleTopAndBottom(164), scaleTopAndBottom(164)));
    }];
    LKBaseLabel *topLabel = [LKBaseLabel labelWithFrame:CGRectZero text:self.model.cate_name textColor:COLOR_HEX(0x333333) font:[UIFont fontWithName:@"PingFangSC-Regular" size:16] textAlignment:NSTextAlignmentCenter];
    [bgView addSubview:topLabel];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_erweimaImageV.mas_bottom).offset(10);
        make.centerX.equalTo(bgView);
    }];
    LKBaseLabel *bottomLabel = [LKBaseLabel labelWithFrame:CGRectZero text:self.model.no_number textColor:COLOR_HEX(0x333333) font:[UIFont fontWithName:@"PingFangSC-Regular" size:16] textAlignment:NSTextAlignmentCenter];
    [bgView addSubview:bottomLabel];
    [bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topLabel.mas_bottom).offset(5);
        make.centerX.equalTo(bgView);
    }];
    UIView *picturesView = [[UIView alloc] init];
    [bgView addSubview:picturesView];
    [picturesView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgView.mas_bottom).offset(-10);
        make.centerX.equalTo(bgView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(WIDTH - 40, scaleTopAndBottom(40)));
    }];
    [self createButtonsArrayWithbgView:picturesView AndTitlesArray:@[@"支付宝",@"微信",@"云闪付",@"VIP"] AndPicturesArray:@[@"ic_qr_collection_ali_pay",@"ic_qr_collection_we_chat",@"ic_qr_collection_cloud_pay",@"ic_qr_collection_vip_card"]];
    return bgView;
}
-(void)createButtonsArrayWithbgView:(UIView *)bgView AndTitlesArray:(NSArray *)titlesArray AndPicturesArray:(NSArray *)picturesArray{
    NSMutableArray *viewsArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < titlesArray.count; i++) {
        UIView *subView = [[UIView alloc] init];
        subView.backgroundColor = [UIColor whiteColor];
        [bgView addSubview:subView];
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = [UIImage imageNamed:picturesArray[i]];
        [subView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(subView.mas_top).offset(0);
            make.centerX.equalTo(subView);
            make.size.mas_equalTo(CGSizeMake(scaleTopAndBottom(30), scaleTopAndBottom(30)));
        }];
        LKBaseLabel *titleLabel = [LKBaseLabel labelWithFrame:CGRectZero text:titlesArray[i] textColor:COLOR_HEX(0x666666) font:[UIFont fontWithName:@"PingFangSC-Regular" size:10] textAlignment:NSTextAlignmentCenter];
        [subView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(5);
            make.centerX.equalTo(subView);
            
        }];
        [viewsArray addObject:subView];
    }
    [viewsArray mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:0 leadSpacing:0 tailSpacing:0];
    [viewsArray mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(bgView.height);
    }];
}
//图片保存成功调用
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        // 保存失败
        [SVProgressHUD showInfoWithStatus:@"图片保存失败"];
    } else {
        [SVProgressHUD showInfoWithStatus:@"图片保存成功"];
        // 保存成功
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
